package controller

import (
	"context"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"user_bff/forms"
	"user_bff/global"
	"user_bff/pkg"
	"user_bff/user_proto"
)

// 用户登录
func UserLogin(c *gin.Context) {
	var form forms.LoginUserForm
	if err := c.ShouldBind(&form); err != nil {
		ReturnErrorJson(err, c)
		return
	}
	comment := pkg.Comment()
	mobile, err := comment.GetUserByMobile(context.Background(), &user_proto.GetUserByMobileRequest{
		Mobile: form.Mobile,
	})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "用户不存在",
			"data": nil,
		})
		return
	}
	password, _ := comment.CheckPassword(context.Background(), &user_proto.CheckPasswordRequest{
		Password:          form.Password,
		EncryptedPassword: mobile.Password,
	})
	if !password.Success {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	verify := store.Verify(form.CaptchaId, form.Captcha, true)
	if !verify {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "图形验证码错误",
			"data": nil,
		})
		return
	}
	marshal, _ := json.Marshal(mobile)
	token, err := pkg.SetJwtToken(string(marshal), int64(global.ServerConfig.JwtConfig.AccessTokenExpireTime), int64(global.ServerConfig.JwtConfig.RefreshTokenExpireTime))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": map[string]interface{}{
			"AccessToken":               token.AccessToken,
			"RefreshToken":              token.RefreshToken,
			"Access_token_expire_time":  global.ServerConfig.JwtConfig.AccessTokenExpireTime,
			"Refresh_token_expire_time": global.ServerConfig.JwtConfig.RefreshTokenExpireTime,
		},
	})
}

// 刷新token
func RefreshToken(c *gin.Context) {
	refreshToken := c.PostForm("refresh_token")
	token, err := pkg.RefreshAccessToken(refreshToken, 3600)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "刷新令牌失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": -1,
		"msg":  "刷新令牌成功",
		"data": map[string]interface{}{
			"AccessToken":               token,
			"RefreshToken":              refreshToken,
			"Access_token_expire_time":  global.ServerConfig.JwtConfig.AccessTokenExpireTime,
			"Refresh_token_expire_time": global.ServerConfig.JwtConfig.RefreshTokenExpireTime,
		},
	})
}
